﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Cosmetic.Logic;
using System.Collections;
using System.Configuration;
using Cosmetic;
using Cosmetic.DataEntity;
using JZSMS_CSharp;
using System.Data;
using System.Data.SqlClient;


namespace WebApp.Shopping
{
    public partial class shopCart : PageBase
    {
        OrderManager theOrderManger = new OrderManager();
        private infor m_infor = new infor();
        private User m_user = new User();
        private Order m_Order;
        PurchaseManager m_PurchaseManager = new PurchaseManager();
        ProductManager m_ProductManager = new ProductManager();
        PackageSaleManager m_PackageSaleManager = new PackageSaleManager();
        UserManager m_UserManager = new UserManager();
        IntegralManager m_IntegralManager = new IntegralManager();
        decimal Coefficient = Convert.ToDecimal(ConfigurationManager.AppSettings["PointCoefficient"].ToString());
        SaleManager m_salemanager = new SaleManager();
        DiscountCardManger m_DiscountCardManger = new DiscountCardManger();
        CashCardManger m_CashCardManger = new CashCardManger();
        decimal m_Price;
        decimal OffRateOfCloth = 1.00m;
        decimal OffRateOfCosmecit = 2.00m;
        decimal OffRateOfSmallGoods = 3.00m;
        decimal OffRateOfOthers = 4.00m;
        decimal p_Price;
        public int CountOflvCart = 0;
        infoManger theinfoManger = new infoManger();
        string strServer, strUserName, strPassword, strdestMobile, strContext, StrDate_From, StrDate_To;

        public static string conn = System.Configuration.ConfigurationManager.ConnectionStrings["CosmeticConnectionString"].ConnectionString;
        protected void Page_Load(object sender, EventArgs e)
        {

            if (!IsPostBack)
            {
                if (null == this.SignInUser)
                {
                    this.Response.Redirect(String.Format("~/Login.aspx?R={0}", this.Request.Url.PathAndQuery));
                    return;
                }
                Session["bookcart"] = null;
                Session["pointcart"] = null;
                if (Session["buycart"] != null && (Session["buycart"] as Hashtable).Count != 0)
                {
                    m_Price = 0;
                    BindCart();
                    CountOflvCart = lvCart.Items.Count;
                    literalProductCount.Text = ProductCount();
                }
                if (Session["buycarts"] != null)
                {
                    Session["buycarts"] = null;
                }
                if (Session["packagecart"] != null && (Session["packagecart"] as Hashtable).Count != 0)
                {
                    p_Price = 0;

                }

                this.lbAfterAllPrice.Text = (this.m_Price + this.p_Price).ToString("F2");

                if (Session["integral"] != null)
                {

                }

                Session["shop"] = "非兑酒";

                literalProductName.Text = "";//商品名称.
            }
            if (this.lvCart.Items.Count != 0)
            {
                this.plseperate.Visible = true;
            }
        }
        public void BindTop()
        {
            //SqlConnection con = new SqlConnection(conn);
            //string sql = "select Name from Category";
            //SqlCommand cmd = new SqlCommand(sql, con);
            //con.Open();
            //SqlDataReader dr = cmd.ExecuteReader();
            //BulletedList1.DataTextField = "Name";
            //BulletedList1.DataSource = dr;
            //BulletedList1.DataBind();
            //con.Close();
        }



        private void BindCart()
        {
            this.lvCart.DataSource = m_ProductManager.GetProducts_Cos((Hashtable)Session["buycart"]);
            this.lvCart.DataBind();

            if (Session["DiscountCart"] != null && (Session["DiscountCart"] as Hashtable).Count != 0)
            {
                this.lvDiscountProduct.DataSource = m_ProductManager.GetProducts_RH((Hashtable)Session["DiscountCart"]);
                this.lvDiscountProduct.DataBind();
            }
        }

        protected void lvCart_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (Session["buycart"] != null && (Session["buycart"] as Hashtable).Count != 0)
            {
                Hashtable ht = Session["buycart"] as Hashtable;

                string pid = (e.Item.FindControl("HFPid") as HiddenField).Value;
                string marketPrice = (e.Item.FindControl("hfMarketPrice") as HiddenField).Value;

                TextBox txtcount = e.Item.FindControl("txtCount") as TextBox;
                if (txtcount != null)
                {
                    txtcount.Text = ht[pid].ToString();
                }

                //计算小计价格
                Label lblSmallCount = e.Item.FindControl("SmallCountNew") as Label;
                decimal uintprice = decimal.Parse((e.Item.FindControl("UnitPrice") as Label).Text);
                int count = Convert.ToInt32(ht[pid].ToString());
                Session["count"] = ht[pid].ToString();
                if (m_salemanager.CheckSaleProduct(pid) && count >= 2)
                {
                    //每买2件sale的商品能按比例打折
                    m_Price += (uintprice * (count / 2) * 2 * m_salemanager.GetDiscountRatio() + (count % 2) * uintprice);
                    lblSmallCount.Text = (uintprice * (count / 2) * 2 * m_salemanager.GetDiscountRatio() + (count % 2) * uintprice).ToString("F2");
                }
                else
                {
                    //累加总价
                    this.m_Price = m_Price + uintprice * count;//).ToString("F2");
                    lblSmallCount.Text = (uintprice * count).ToString("F2");
                }
                Label labSave = e.Item.FindControl("labSaveMoney") as Label;//// 优惠价格.
                //优惠价格= 总价－单价*数量
                labSave.Text = ((decimal.Parse(marketPrice) * count) - decimal.Parse(lblSmallCount.Text)).ToString();
            }
        }

        protected void TextBox1_TextChanged(object sender, EventArgs e)
        {
            string Id = (sender as TextBox).ToolTip;
            TextBox txt = sender as TextBox;
            (Session["buycart"] as Hashtable)[Id] = txt.Text;
            if (int.Parse(txt.Text) > 10000 || int.Parse(txt.Text) < 1)
            {
                txt.Text = "1";
                (Session["buycart"] as Hashtable)[Id] = "1";
                ScriptManager.RegisterStartupScript(this.Page, Page.GetType(), "openalert", "alert('必须输入1-10000之间的数');", true);
                return;
            }
            Response.Redirect(Request.Url.ToString());
        }

        private string ProductCount()
        {
            int a = 0;
            foreach (ListViewDataItem item in this.lvCart.Items)
            {
                TextBox tb = item.FindControl("txtCount") as TextBox;
                if (tb != null)
                {
                    a += int.Parse(tb.Text);
                }
            }
            foreach (ListViewDataItem item in this.lvDiscountProduct.Items)
            {
                a += 1;
            }
            return a.ToString();
        }

        //protected void CBCheckAll_CheckedChanged(object sender, EventArgs e)
        //{
        //    foreach (ListViewDataItem item in this.lvCart.Items)
        //    {
        //        (item.FindControl("CheckBox1") as CheckBox).Checked = this.CBCheckAll.Checked;
        //    }

        //}

        protected void LinkButton1_Click(object sender, EventArgs e)
        {
            int ckCount = 0;
            int ckCount_Dis = 0;
            foreach (ListViewDataItem item in this.lvCart.Items)
            {
                if ((item.FindControl("CheckBox1") as CheckBox).Checked == true)
                {
                    ckCount++;
                }
            }
            foreach (ListViewDataItem item in this.lvDiscountProduct.Items)
            {
                if ((item.FindControl("CheckBox1_Dis") as CheckBox).Checked == true)
                {
                    ckCount_Dis++;
                }
            }

            if (lvDiscountProduct.Items.Count > ckCount_Dis && lvCart.Items.Count == ckCount)
            {
                Page.RegisterStartupScript("openalert", "<script>alert('不能只单买打折的商品。');</script>");
                return;
            }


            foreach (ListViewDataItem item in this.lvCart.Items)
            {
                if ((item.FindControl("CheckBox1") as CheckBox).Checked == true)
                {
                    string pid = (item.FindControl("HFPid") as HiddenField).Value;

                    (Session["buycart"] as Hashtable).Remove(pid);
                    (Session["size"] as Hashtable).Remove(pid);

                }
            }

            foreach (ListViewDataItem item in this.lvDiscountProduct.Items)
            {
                if ((item.FindControl("CheckBox1_Dis") as CheckBox).Checked == true)
                {
                    string pid = (item.FindControl("HFPid_dis") as HiddenField).Value;

                    (Session["DiscountCart"] as Hashtable).Remove(pid);
                    //(Session["size"] as Hashtable).Remove(pid);

                }
            }
            Response.Redirect(Request.Url.ToString());
        }


        protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
        {
            Response.Redirect("../index.htm");
        }

        protected void ImageButton2_Click(object sender, ImageClickEventArgs e)
        {

            Response.Redirect("../index.htm");
        }
        protected void ImageButton3_Click(object sender, ImageClickEventArgs e)
        {
            //if (this.TextBox3.Text == "")
            //{
            //    Page.RegisterStartupScript("openalert", "<script>alert('请输入您的订单号查询');</script>");
            //    return;
            //}
            //Response.Redirect("~/Space/MyaccountManager/OrderRecords.aspx?contetns=" + this.TextBox3.Text.Trim());

        }
        //判断是否注册/sesion 传至
        protected void LinkButton2_Click(object sender, EventArgs e)
        {

        }

        private string GenerateCheckCode()
        {
            int number;
            char code;
            string checkCode = String.Empty;

            System.Random random = new Random();
            for (int i = 0; i < 5; i++)
            {
                number = random.Next();

                if (number % 2 == 0)
                    code = (char)('0' + (char)(number % 10));
                else
                    code = (char)('A' + (char)(number % 26));

                checkCode += code.ToString();
            }
            return checkCode;
        }



        protected void imgBtnGoPay_Click(object sender, EventArgs e)
        {
            if (null == this.SignInUser)
            {
                this.Response.Redirect(String.Format("~/Login.aspx?R={0}", this.Request.Url.PathAndQuery));
                return;
            }
            if (this.lvCart.Items.Count == 0)
            {
                //Page.RegisterStartupScript("openalert", "<script>alert('购物车为空');</script>");
                return;
            }
            Order theOrder = new Order();
            theOrder.Price = decimal.Parse(this.lbAfterAllPrice.Text);
            if (this.HFDiscountCardId.Value != "")
            {
                theOrder.UsedDiscountCardId = this.HFDiscountCardId.Value;
                theOrder.UseDiscountCard = decimal.Parse(this.HFDiscountAmount.Value);
            }
            else
            {
                theOrder.UsedDiscountCardId = "";
                theOrder.UseDiscountCard = 0;
            }
            if (this.HFCashCardId.Value != "")
            {
                theOrder.UsedCashCardId = this.HFCashCardId.Value;
                theOrder.UseCashCard = decimal.Parse(this.HFCashCardAmount.Value);
            }
            else
            {
                theOrder.UsedCashCardId = "";
                theOrder.UseCashCard = 0;
            }

            Session["Order"] = theOrder;
            m_Order = (Order)Session["Order"];
            Response.Redirect("~/Shopping/orderconfirmation.aspx");
            //Cosmetic.DataEntity.User theUser = this.m_UserManager.LoginValidateBytel(this.TextBox4.Text.Trim());
            //if (null == theUser)
            //{
            //    m_user.tel = this.TextBox4.Text;
            //    m_user.Level = "普通会员";
            //    m_user.Status = false;
            //    m_user.UserId = Guid.NewGuid();
            //    m_user.Password = GenerateCheckCode();
            //    m_user.RegisterTime = DateTime.Now;
            //    m_UserManager.Insert(m_user);
            //    Cosmetic.DataEntity.User theusers = this.m_UserManager.GetUserBytel(this.TextBox4.Text);
            //    Session["userid"] = theusers.UserId;
            //    Session["tel"] = theusers.tel;
            //    Session["SignInUser"] = theUser;
            //    //服务器地址
            //    strServer = "http://www.jianzhou.sh.cn:8080/JianzhouSMSWSServer/services/BusinessService";
            //    //用户名
            //    strUserName = "cjz509";
            //    //密码
            //    strPassword = "123456";
            //    //目标号码
            //    strdestMobile = this.TextBox4.Text;
            //    //短信内容
            //    strContext = "恭喜您成为jj-9原装进口葡萄酒在线商城,您的用户名：'" + this.TextBox4.Text + "',密码是：'" + m_user.Password + "'";
            //    //检索一定时间内的定时发送时间格式为 yyyyymmddhhss
            //    //StrDate_From = DateTime.Now;
            //    //StrDate_To = DateTime.Now;
            //    //发送短信
            //    SMS.sendMessageBySingle(strServer, strUserName, strPassword, strdestMobile, strContext).ToString();
            //    Response.Redirect("~/Shopping/checkOut.aspx");
            //}
            //else
            //{
            //    Cosmetic.DataEntity.Order theorder = this.theOrderManger.CheckExistes(this.TextBox4.Text.Trim());

            //    if (null == theorder)
            //    {
            //        Cosmetic.DataEntity.User theusers = this.m_UserManager.GetUserBytel(this.TextBox4.Text);
            //        Session["userid"] = theusers.UserId;
            //        Session["tel"] = theusers.tel;
            //        Session["SignInUser"] = theusers;
            //       
            //    }
            //    else
            //    {
            //        Cosmetic.DataEntity.User theusers = this.m_UserManager.GetUserBytel(this.TextBox4.Text);
            //        Session["userid"] = theusers.UserId;
            //        Session["tel"] = theusers.tel;
            //        Session["SignInUser"] = theusers;
            //        ;
            //    }


            //}

        }

        protected void lvDiscountProduct_ItemDataBound(object sender, ListViewItemEventArgs e)
        {
            if (Session["DiscountCart"] != null && (Session["DiscountCart"] as Hashtable).Count != 0)
            {
                Hashtable ht = Session["DiscountCart"] as Hashtable;

                string pid = (e.Item.FindControl("HFPid_dis") as HiddenField).Value;
                string marketPrice = (e.Item.FindControl("hfMarketPrice_dis") as HiddenField).Value;

                //TextBox txtcount = e.Item.FindControl("txtCount_Dis") as TextBox;
                //if (txtcount != null)
                //{
                //    txtcount.Text = ht[pid].ToString();
                //}

                //计算小计价格
                Label lblSmallCount = e.Item.FindControl("SmallCountNew_Dis") as Label;
                decimal uintprice = decimal.Parse((e.Item.FindControl("UnitPrice_Dis") as Label).Text);
                int count = Convert.ToInt32(ht[pid].ToString());
                Session["count"] = ht[pid].ToString();
                if (m_salemanager.CheckSaleProduct(pid) && count >= 2)
                {
                    //每买2件sale的商品能按比例打折
                    m_Price += (uintprice * (count / 2) * 2 * m_salemanager.GetDiscountRatio() + (count % 2) * uintprice);
                    lblSmallCount.Text = (uintprice * (count / 2) * 2 * m_salemanager.GetDiscountRatio() + (count % 2) * uintprice).ToString("F2");
                }
                else
                {
                    //累加总价
                    this.m_Price = m_Price + uintprice * count;//).ToString("F2");
                    lblSmallCount.Text = (uintprice * count).ToString("F2");
                }
                Label labSave = e.Item.FindControl("labSaveMoney_Dis") as Label;//// 优惠价格.
                //优惠价格= 总价－单价*数量
                labSave.Text = ((decimal.Parse(marketPrice) * count) - decimal.Parse(lblSmallCount.Text)).ToString();
            }
        }
    }//end class
}
